﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web.Mvc;
using DataAccess.DB;
using DuocThaiBinh.Common;
using DuocThaiBinh.HtmlHelpers;
using DuocThaiBinh.HtmlHelpers.ExportToExcel;
using Newtonsoft.Json;
using PagedList;

namespace DuocThaiBinh.Controllers
{
    public class XuatKhoController : BaseController
    {
        private db_YTeTBEntities db = new db_YTeTBEntities();

        [Authorize(Roles = "Administrator,StaffXuatKho")]
        public ActionResult IndexGrid()
        {
            return View();
        }

        [Authorize(Roles = "Administrator,StaffXuatKho")]
        public JsonResult IndexGridGet(int page, int rows, string sidx, string sord, string from, string to, string filters, bool _search, string masp)
        {
            List<XuatKho> _XuatKhoes = new List<XuatKho>();
            int currentCuaHangID = Convert.ToInt32(Session["CuaHangID"]);
            var khachhangs = db.KhachHangs.Where(k => k.CuaHangID == currentCuaHangID).ToList();
            foreach (var khachhang in khachhangs)
            {
                var temp = db.XuatKhoes.OrderByDescending(p => p.MaHoaDon).Where(p => p.KhachHang.ID == khachhang.ID);

                if (!string.IsNullOrEmpty(from))
                {
                    temp = temp.Where(p => p.NgayXuatKho >= Util.ConvertObjectToDateTime(from));
                }

                if (!string.IsNullOrEmpty(to))
                {
                    temp = temp.Where(p => p.NgayXuatKho <= Util.ConvertObjectToDateTime(to));
                }
                if (!string.IsNullOrEmpty(masp))
                {
                    temp = temp.Where(p => p.Ma_SP != null && p.Ma_SP.ToLower().Contains(masp.ToLower()));
                }

                if (temp != null)
                {
                    _XuatKhoes.AddRange(temp.ToList());
                }
            }

            var XuatKhoes = _XuatKhoes as IEnumerable<XuatKho>;

            if (_search)
            {
                FiltersJq f = (!_search || string.IsNullOrEmpty(filters)) ? null : JsonConvert.DeserializeObject<FiltersJq>(filters);
                for (int i = 0; i < f.rules.Count; i++)
                {
                    string field = f.rules[i].field;
                    string data = f.rules[i].data;
                    switch (field)
                    {
                        case "MaHoaDon": XuatKhoes = XuatKhoes.Where(p => p.MaHoaDon.ToLower().Contains(data.ToLower())); break;
                        case "MaKH": XuatKhoes = XuatKhoes.Where(p => p.KhachHang.MaKH.ToLower().Contains(data.ToLower())); break;
                        //case "DiaChiKH": XuatKhoes = XuatKhoes.Where(p => p.KhachHang.DiaChiKH.ToLower().Contains(data.ToLower())); break;
                        case "HoTen": XuatKhoes = XuatKhoes.Where(p => p.UserProfile.DisplayName.ToLower().Contains(data.ToLower())); break;
                        //case "NgayXuatKho": XuatKhoes = XuatKhoes.Where(p => EntityFunctions.TruncateTime(p.NgayXuatKho) == EntityFunctions.TruncateTime(DateTime.Now)); break;
                        //case "TongThanhToan": XuatKhoes = XuatKhoes.Where(p => p.TongThanhToan.ToLower().Contains(data.ToLower())); break;
                        default: XuatKhoes.Where(p => p.MaHoaDon.ToLower().Contains(data.ToLower())); break;
                    }
                }

            }

            var count = XuatKhoes.Count<XuatKho>();
            int total;
            if (count == 0)
                total = 0;
            else
                total = (int)Math.Ceiling((decimal)count / rows);

            var pagedResult = XuatKhoes.Skip(rows * (page - 1)).Take(rows).ToList();

            return Json(new
            {
                page = page,
                total = total,
                records = count,
                rows = pagedResult.Select(x => new { x.ID, x.MaHoaDon, x.KhachHang.MaKH, x.KhachHang.DiaChiKH, x.UserProfile.DisplayName, x.NgayXuatKho, x.TongThanhToan })
            }, JsonRequestBehavior.AllowGet);
        }

        [Authorize(Roles = "Administrator,StaffXuatKho")]
        public ExcelResult Export(string sidx, string sord, string from, string to, string masp, string filter, bool search)
        {
            List<XuatKho> _XuatKhoes = new List<XuatKho>();
            int currentCuaHangID = Convert.ToInt32(Session["CuaHangID"]);
            var khachhangs = db.KhachHangs.Where(k => k.CuaHangID == currentCuaHangID).ToList();
            foreach (var khachhang in khachhangs)
            {
                var temp = db.XuatKhoes.OrderByDescending(p => p.MaHoaDon).Where(p => p.KhachHang.MaKH != null);

                if (!string.IsNullOrEmpty(from))
                {
                    temp = temp.Where(p => p.NgayXuatKho >= Util.ConvertObjectToDateTime(from));
                }

                if (!string.IsNullOrEmpty(to))
                {
                    temp = temp.Where(p => p.NgayXuatKho <= Util.ConvertObjectToDateTime(to));
                }
                if (!string.IsNullOrEmpty(masp))
                {
                    temp = temp.Where(p => p.Ma_SP != null && p.Ma_SP.ToLower().Contains(masp.ToLower()));
                }

                if (temp != null)
                {
                    _XuatKhoes.AddRange(temp.ToList());
                }
            }

            var XuatKhoes = _XuatKhoes as IEnumerable<XuatKho>;
            if (search)
            {
                FiltersJq fil = (!search || string.IsNullOrEmpty(filter)) ? null : JsonConvert.DeserializeObject<FiltersJq>(filter);
                for (int i = 0; i < fil.rules.Count; i++)
                {
                    string field = fil.rules[i].field;
                    string data = fil.rules[i].data;
                    switch (field)
                    {
                        case "MaHoaDon": XuatKhoes = XuatKhoes.Where(p => p.MaHoaDon.ToLower().Contains(data.ToLower())); break;
                        case "MaKH": XuatKhoes = XuatKhoes.Where(p => p.KhachHang.MaKH.ToLower().Contains(data.ToLower())); break;
                        case "DiaChiKH": XuatKhoes = XuatKhoes.Where(p => p.KhachHang.DiaChiKH.ToLower().Contains(data.ToLower())); break;
                        case "HoTen": XuatKhoes = XuatKhoes.Where(p => p.UserProfile.DisplayName.ToLower().Contains(data.ToLower())); break;
                        default: XuatKhoes.Where(p => p.MaHoaDon.ToLower().Contains(data.ToLower())); break;
                    }
                }

            }

            decimal tongthanhtoan = 0;
            DataTable tablenew = new DataTable("Xuatkho");
            tablenew.Columns.Add("Mã hóa đơn");
            tablenew.Columns.Add("Khách hàng");
            tablenew.Columns.Add("Nv.Giao Dịch");
            tablenew.Columns.Add("Ngày xuất kho");
            tablenew.Columns.Add("Tổng thanh toán");

            foreach (XuatKho xuatkho in XuatKhoes)
            {
                DataRow newrow = tablenew.NewRow();
                newrow["Mã hóa đơn"] = xuatkho.MaHoaDon;
                newrow["Khách hàng"] = xuatkho.KhachHang.TenKH;
                newrow["Nv.Giao Dịch"] = xuatkho.UserProfile.DisplayName;
                DateTime dt = Convert.ToDateTime(xuatkho.NgayXuatKho);
                newrow["Ngày xuất kho"] = dt.ToString("dd/MM/yyyy");
                var tongtt = xuatkho.TongThanhToan;
                newrow["Tổng thanh toán"] = tongtt;
                tongthanhtoan += Util.ConvertCurrencyToMoney(tongtt);
                tablenew.Rows.Add(newrow);
            }
            DataRow newrow1 = tablenew.NewRow();
            newrow1["Nv.Giao Dịch"] = "Tổng :";
            newrow1["Tổng thanh toán"] = Util.ConvertDecimaToCurrency(tongthanhtoan);
            tablenew.Rows.Add(newrow1);
            string excelFilename = "Thống kê xuất kho ngày " + DateTime.Now.ToString("dd/MM/yyyy") + ".xlsx";
           
            var stream = CreateExcelFile.CreateExcelDocument(tablenew, excelFilename);

            return new ExcelResult()
            {
                FileName = excelFilename,
                Stream = stream
            };

        }

        [Authorize(Roles = "Administrator,StaffXuatKho")]
        public ActionResult Index(string txtSearch, string dtFrom, string dtTo, int? page, string ID_NguoiXuatKho, string SearchMaSP, string currentFilter, string txtMHD, string crFr, string crTo)
        {
            List<XuatKho> XuatKhoes = new List<XuatKho>();
            int currentCuaHangID = Convert.ToInt32(Session["CuaHangID"]);
            var khachhangs = db.KhachHangs.Where(k => k.CuaHangID == currentCuaHangID).ToList();
            foreach (var khachhang in khachhangs)
            {
                var temp = db.XuatKhoes.Include(n => n.KhachHang).Include(n => n.UserProfile).Where(n => n.ID_KhachHang == khachhang.ID);
                if (temp != null)
                {
                    XuatKhoes.AddRange(temp.ToList());
                }
            }

            if (txtSearch != null)
            {
                page = 1;
            }
            else
            {
                txtSearch = currentFilter;
            }
            ViewBag.CurrentFilter = txtSearch;
            if (dtFrom != null)
            {
                page = 1;
            }
            else
            {
                dtFrom = crFr;
            }
            ViewBag.crFr = dtFrom;

            if (dtTo != null)
            {
                page = 1;
            }
            else
            {
                dtTo = crTo;
            }
            ViewBag.crTo = dtTo;

            if (!string.IsNullOrEmpty(txtSearch))
            {
                XuatKhoes = XuatKhoes.Where(p => p.KhachHang.MaKH != null && p.KhachHang.MaKH.ToLower().Equals(txtSearch.ToLower())).ToList();
            }
            if (!string.IsNullOrEmpty(dtFrom))
            {
                XuatKhoes = XuatKhoes.Where(p => p.NgayXuatKho >= Util.ConvertObjectToDateTime(dtFrom)).ToList();
            }

            if (!string.IsNullOrEmpty(dtTo))
            {
                XuatKhoes = XuatKhoes.Where(p => p.NgayXuatKho <= Util.ConvertObjectToDateTime(dtTo)).ToList();
            }

            if (!string.IsNullOrEmpty(ID_NguoiXuatKho))
            {
                XuatKhoes = XuatKhoes.Where(p => p.ID_NguoiXuatKho == Convert.ToInt32(ID_NguoiXuatKho)).ToList();
            }
            if (!string.IsNullOrEmpty(SearchMaSP))
            {
                XuatKhoes = XuatKhoes.Where(p => p.Ma_SP != null && p.Ma_SP.ToLower().Contains(SearchMaSP.ToLower())).ToList();
            }
            if (!string.IsNullOrEmpty(txtMHD))
            {
                XuatKhoes = XuatKhoes.Where(p => p.MaHoaDon.ToLower().Contains(txtMHD.ToLower())).ToList();
            }

            ViewBag.CurrentFilter = txtSearch;

            ViewBag.ID_NguoiXuatKho = new SelectList(db.UserProfiles, "UserId", "Code");
            ViewBag.SelectMenu = "1";
            int pageSize = 50;
            int pageNumber = (page ?? 1);
            return View(XuatKhoes.OrderByDescending(p => p.MaHoaDon).ToPagedList(pageNumber, pageSize));
        }

        [Authorize(Roles = "Administrator,StaffXuatKho")]
        public ActionResult IndexHDTT(string txtSearch, string dtFrom, string dtTo, int? page, string ID_NguoiXuatKho)
        {
            List<XuatKho> XuatKhoes = new List<XuatKho>();
            int currentCuaHangID = Convert.ToInt32(Session["CuaHangID"]);
            var khachhangs = db.KhachHangs.Where(k => k.CuaHangID == currentCuaHangID).ToList();
            foreach (var khachhang in khachhangs)
            {
                var temp = db.XuatKhoes.Include(n => n.KhachHang).Include(n => n.UserProfile).Where(p => p.IsThanhToan == "yes" && p.ID_KhachHang == khachhang.ID).ToList();

                if (!string.IsNullOrEmpty(txtSearch))
                {
                    temp = temp.Where(p => p.KhachHang.MaKH.ToLower().Contains(txtSearch.ToLower())).ToList();
                }
                if (!string.IsNullOrEmpty(dtFrom))
                {
                    temp = temp.Where(p => p.NgayXuatKho >= DateTime.ParseExact(dtFrom, "dd/MM/yyyy", null)).ToList();
                }
                if (!string.IsNullOrEmpty(dtTo))
                {
                    temp = temp.Where(p => p.NgayXuatKho <= DateTime.ParseExact(dtTo, "dd/MM/yyyy", null)).ToList();
                }

                if (!string.IsNullOrEmpty(ID_NguoiXuatKho))
                {
                    temp = temp.Where(p => p.ID_NguoiXuatKho == Convert.ToInt32(ID_NguoiXuatKho)).ToList();
                }

                if (temp != null)
                {
                    XuatKhoes.AddRange(temp.ToList());
                }                
            }

            ViewBag.ID_NguoiXuatKho = new SelectList(db.UserProfiles, "UserId", "Code");

            int pageSize = 50;
            int pageNumber = (page ?? 1);
            return View(XuatKhoes.OrderByDescending(p => p.MaHoaDon).ToPagedList(pageNumber, pageSize));
        }


        public SanPham GetSPByMaSP(string masp)
        {
            var sp = (db.SanPhams.Where(p => p.MaSP == masp.Replace(";#", "")).FirstOrDefault());

            return sp;
        }

        [Authorize(Roles = "Administrator,StaffXuatKho")]
        public ActionResult IndexThongKeSanPham()
        {
            List<XuatKho> XuatKhoes = new List<XuatKho>();
            string txtSearchDVCC = Request.QueryString["khachhang"];
            string dtFrom = Request.QueryString["from"];
            string dtTo = Request.QueryString["to"];
            string id_nv = Request.QueryString["nv"];
            int currentCuaHangID = Convert.ToInt32(Session["CuaHangID"]);
            var khachhangs = db.KhachHangs.Where(k => k.CuaHangID == currentCuaHangID).ToList();
            foreach (var khachhang in khachhangs)
            {
                var temp = db.XuatKhoes.Include(n => n.KhachHang).Include(n => n.UserProfile).Where(n => n.ID_KhachHang == khachhang.ID).OrderByDescending(p => p.ID).ToList();

                if (!string.IsNullOrEmpty(txtSearchDVCC))
                {
                    temp = temp.Where(p => p.KhachHang.MaKH.ToLower().Equals(txtSearchDVCC.ToLower())).ToList();
                    KhachHang kh = db.KhachHangs.Where(p => p.MaKH == txtSearchDVCC).FirstOrDefault();
                    ViewBag.TenKH = kh.TenKH;
                }

                if (!string.IsNullOrEmpty(dtFrom))
                {
                    temp = temp.Where(p => p.NgayXuatKho >= Util.ConvertObjectToDateTime(dtFrom)).ToList();
                }
                if (!string.IsNullOrEmpty(dtTo))
                {
                    temp = temp.Where(p => p.NgayXuatKho <= Util.ConvertObjectToDateTime(dtTo)).ToList();
                }
                if (!string.IsNullOrEmpty(id_nv))
                {
                    temp = temp.Where(p => p.ID_NguoiXuatKho == Convert.ToInt32(id_nv)).ToList();
                }

                if (temp != null)
                {
                    XuatKhoes.AddRange(temp.ToList());
                }
            }

            Dictionary<string, int> listSP = new Dictionary<string, int>();
            foreach (XuatKho xuatkho in XuatKhoes)
            {
                var listMASP = xuatkho.Ma_SP.Split(new string[] { ";#" }, StringSplitOptions.RemoveEmptyEntries);
                var listSoLuong = xuatkho.SoLuong.Split(new string[] { ";#" }, StringSplitOptions.RemoveEmptyEntries);
                for (int i = 0; i < listMASP.Length; i++)
                {
                    if (!listSP.Keys.Contains(listMASP[i]))
                    {
                        listSP.Add(listMASP[i], Convert.ToInt32(listSoLuong[i]));
                    }
                    else
                    {
                        listSP[listMASP[i]] = listSP[listMASP[i]] + Convert.ToInt32(listSoLuong[i]);
                    }
                }
            }
            ViewBag.ListSP = listSP;

            ViewBag.dtFrom = dtFrom;
            ViewBag.dtTo = dtTo;


            return View();

        }

        [Authorize(Roles = "Administrator,StaffXuatKho")]
        public ActionResult IndexThongKe()
        {
            List<XuatKho> XuatKhoes = new List<XuatKho>();
            string txtSearchDVCC = Request.QueryString["khachhang"];
            string dtFrom = Request.QueryString["from"];
            string dtTo = Request.QueryString["to"];
            string strNhanVien = Request.QueryString["nv"];
            string masp = Request.QueryString["masp"];
            int currentCuaHangID = Convert.ToInt32(Session["CuaHangID"]);
            var khachhangs = db.KhachHangs.Where(k => k.CuaHangID == currentCuaHangID).ToList();
            foreach (var khachhang in khachhangs)
            {
                var temp = db.XuatKhoes.Include(n => n.KhachHang).Include(n => n.UserProfile).Where(n => n.ID_KhachHang == khachhang.ID).OrderByDescending(p => p.ID).ToList();

                if (!string.IsNullOrEmpty(txtSearchDVCC))
                {
                    temp = temp.Where(p => p.KhachHang.MaKH != null && p.KhachHang.MaKH.ToLower().Equals(txtSearchDVCC.ToLower())).ToList();
                }

                if (!string.IsNullOrEmpty(dtFrom))
                {
                    temp = temp.Where(p => p.NgayXuatKho >= Util.ConvertObjectToDateTime(dtFrom)).ToList();
                }
                if (!string.IsNullOrEmpty(dtTo))
                {
                    temp = temp.Where(p => p.NgayXuatKho <= Util.ConvertObjectToDateTime(dtTo)).ToList();
                }
                if (!string.IsNullOrEmpty(strNhanVien))
                {
                    temp = temp.Where(p => p.UserProfile.DisplayName.ToLower().Contains(strNhanVien)).ToList();
                }
                if (!string.IsNullOrEmpty(masp))
                {
                    temp = temp.Where(p => p.Ma_SP.Contains(masp + ";#")).ToList();
                }

                if (temp != null)
                {
                    XuatKhoes.AddRange(temp.ToList());
                }
            }

            decimal total = 0;
            decimal totalLai = 0;
            foreach (XuatKho xk in XuatKhoes)
            {
                if (xk.TongThanhToan != null)
                {
                    total += Util.ConvertCurrencyToMoney(xk.TongThanhToan);

                }
                if (xk.Lai != null)
                {
                    totalLai += Util.ConvertCurrencyToMoney(xk.Lai);
                }
            }
            ViewBag.TongXuatKho = Util.ConvertDecimaToCurrency(total);
            ViewBag.TongLai = Util.ConvertDecimaToCurrency(totalLai);
            return View(XuatKhoes.OrderByDescending(p => p.MaHoaDon));
        }



        //
        // GET: /XuatKho/Details/5
        [Authorize(Roles = "Administrator,StaffXuatKho")]
        public ActionResult Details(int id = 0)
        {
            XuatKho xuatkho = db.XuatKhoes.Find(id);
            if (xuatkho == null || xuatkho.KhachHang.CuaHangID != Convert.ToInt32(Session["CuaHangID"]))
            {
                return HttpNotFound();
            }

            var masp = xuatkho.Ma_SP;
            var soluong = xuatkho.SoLuong;
            var gia = xuatkho.Gia;
            var donvi = xuatkho.DonVi;
            List<string> listHSD = new List<string>();
            List<string> listKho = new List<string>();
            List<string> listSP = new List<string>();

            var listMaSanPhams = masp.Split(new string[] { ";#" }, StringSplitOptions.None);
            ViewBag.listmasp = listMaSanPhams;
            ViewBag.listsoLuong = soluong.Split(new string[] { ";#" }, StringSplitOptions.None);
            ViewBag.listgia = gia.Split(new string[] { ";#" }, StringSplitOptions.None);
            ViewBag.listDonvi = donvi.Split(new string[] { ";#" }, StringSplitOptions.None);

            foreach (string maSanPham in listMaSanPhams)
            {
                if (!string.IsNullOrEmpty(maSanPham))
                {
                    SanPham sp = GetSPByMaSP(maSanPham);
                    if (sp != null)
                    {
                        var hansudung = sp.HSD;
                        if (hansudung == null)
                        {
                            listHSD.Add(string.Empty);
                        }
                        else
                        {
                            listHSD.Add(Util.ConvertObjectToStringDateTime(sp.HSD));
                        }
                        ///ChinhNH
                        //listKho.Add(sp.Kho.MaKho);
                        listSP.Add(sp.TenSP);
                    }
                }
            }
            ViewBag.listHSD = listHSD.ToArray();
            ViewBag.listMaKho = listKho.ToArray();
            ViewBag.listSP = listSP.ToArray();

            return View(xuatkho);
        }


        [Authorize(Roles = "Administrator,StaffXuatKho")]
        public ActionResult DetailsXuatKho(int id = 0)
        {
            XuatKho xuatkho = db.XuatKhoes.Find(id);
            if (xuatkho == null || xuatkho.KhachHang.CuaHangID != Convert.ToInt32(Session["CuaHangID"]))
            {
                return HttpNotFound();
            }
            
            var masp = xuatkho.Ma_SP;
            var soluong = xuatkho.SoLuong;
            var gia = xuatkho.Gia;
            var donvi = xuatkho.DonVi;
            List<string> listHSD = new List<string>();
            List<string> listKho = new List<string>();
            List<string> listSP = new List<string>();

            var listMaSanPhams = masp.Split(new string[] { ";#" }, StringSplitOptions.None);
            ViewBag.listmasp = listMaSanPhams;
            ViewBag.listsoLuong = soluong.Split(new string[] { ";#" }, StringSplitOptions.None);
            ViewBag.listgia = gia.Split(new string[] { ";#" }, StringSplitOptions.None);
            ViewBag.listDonvi = donvi.Split(new string[] { ";#" }, StringSplitOptions.None);

            foreach (string maSanPham in listMaSanPhams)
            {
                if (!string.IsNullOrEmpty(maSanPham))
                {
                    SanPham sp = GetSPByMaSP(maSanPham);
                    if (sp != null)
                    {
                        var hansudung = sp.HSD;
                        if (hansudung == null)
                        {
                            listHSD.Add(string.Empty);
                        }
                        else
                        {
                            listHSD.Add(Util.ConvertObjectToStringDateTime(sp.HSD));
                        }
                        ///ChinhNH
                        //listKho.Add(sp.Kho.MaKho);
                        listSP.Add(sp.TenSP);
                    }
                }
            }
            ViewBag.listHSD = listHSD.ToArray();
            ViewBag.listMaKho = listKho.ToArray();
            ViewBag.listSP = listSP.ToArray();

            return View(xuatkho);
        }

        //
        // GET: /XuatKho/Create
        [Authorize(Roles = "Administrator,StaffXuatKho")]
        public ActionResult Create()
        {
            var currentUser = db.UserProfiles.Where(u => u.UserName == User.Identity.Name).FirstOrDefault();
            if (currentUser == null) return RedirectToAction("Index", "Home");
            int currentCuaHangID = Convert.ToInt32(Session["CuaHangID"]);
            string ma = "X-" + currentCuaHangID + "-";
            XuatKho xuatkho = db.XuatKhoes.Where(p => p.MaHoaDon.StartsWith(ma)).OrderByDescending(p => p.MaHoaDon).FirstOrDefault();
            string mahd = string.Empty;
            if (xuatkho != null)
            {
                var MaXKLast = xuatkho.MaHoaDon.Split(new string[] { "-" }, StringSplitOptions.None);
                if (MaXKLast.Length == 4)
                {
                    if (Convert.ToInt32(MaXKLast[MaXKLast.Length - 2]) == DateTime.Now.Month)
                    {
                        var intMaSPnew = Convert.ToInt32(MaXKLast[MaXKLast.Length - 1]) + 1;
                        mahd = ma + DateTime.Now.Year + "-" + string.Format("{0:00}", DateTime.Now.Month) + "-" + string.Format("{0:00000}", intMaSPnew);
                    }
                    else
                    {
                        mahd = ma + DateTime.Now.Year + "-" + string.Format("{0:00}", DateTime.Now.Month) + "-" + "00001";
                    }
                }
                else if (MaXKLast.Length == 5)
                {
                    if (Convert.ToInt32(MaXKLast[MaXKLast.Length - 3]) == DateTime.Now.Month)
                    {
                        var intMaSPnew = Convert.ToInt32(MaXKLast[MaXKLast.Length - 1]) + 1;
                        mahd = ma + DateTime.Now.Year + "-" + string.Format("{0:00}", DateTime.Now.Month) + "-" + string.Format("{0:00000}", intMaSPnew);
                    }
                    else
                    {
                        mahd = ma + DateTime.Now.Year + "-" + string.Format("{0:00}", DateTime.Now.Month) + "-" + "00001";
                    }
                }
                else
                {
                    mahd = ma + DateTime.Now.Year + "-" + string.Format("{0:00}", DateTime.Now.Month) + "-" + "00001";
                }
            }
            else
            {
                mahd = ma + string.Format("{0:00}", DateTime.Now.Month) + "-" + "00001";
            }

            ViewBag.MaHD = mahd;
            ViewBag.ID_KhachHang = new SelectList(db.KhachHangs.OrderBy(p => p.TenKH), "ID", "MaKH");
            List<Kho> khoes = new List<Kho>();
            foreach (var userInCuaHang in currentUser.UserInCuaHangs)
            {
                khoes.AddRange(userInCuaHang.CuaHang.Khoes);
            }
            ViewBag.KhoID = new SelectList(khoes.OrderBy(p => p.TenKho), "ID", "TenKho");
            ViewBag.CurrentUserDisplayName = currentUser.DisplayName;
            ViewBag.CurrentUserID = currentUser.UserId;
            return View();
        }

        public JsonResult CheckUserExist(string ID, string MaHoaDon)
        {
            XuatKho existMaHoaDon = new db_YTeTBEntities().XuatKhoes.Where(p => p.MaHoaDon.Equals(MaHoaDon)).FirstOrDefault();

            if (ID.Equals("undefined"))// mode new
            {
                if (existMaHoaDon != null)
                {
                    return Json(false, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }

            else
            {
                if (existMaHoaDon != null)
                {

                    if (existMaHoaDon.ID != Convert.ToInt32(ID))
                    {
                        return Json(false, JsonRequestBehavior.AllowGet);
                    }
                    else
                    {
                        return Json(true, JsonRequestBehavior.AllowGet);
                    }
                }
                else
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
        }

        //
        // POST: /XuatKho/Create
        [Authorize(Roles = "Administrator,StaffXuatKho")]
        [HttpPost]
        public ActionResult Create(XuatKho xuatkho, FormCollection form)
        {
            var currentUser = db.UserProfiles.Where(u => u.UserName == User.Identity.Name).FirstOrDefault();
            if (currentUser == null) return RedirectToAction("Index", "Home");

            string masp = string.Empty;
            string soluong = string.Empty;
            string gia = string.Empty;
            string donvi = string.Empty;

            List<string> listmasp = new List<string>();
            List<int> listsoluong = new List<int>();
            List<string> listgia = new List<string>();

            if (ModelState.IsValid)
            {
                foreach (string key in form.AllKeys)
                {
                    if (key.Contains("ma_sp"))
                    {
                        masp += form[key] + ";#";
                        listmasp.Add(form[key]);
                    }
                    if (key.Contains("SoLuong_"))
                    {
                        soluong += form[key] + ";#";
                        var valueSL = form[key];
                        int intValueSL = 0;
                        if (int.TryParse(valueSL, out intValueSL))
                        {
                            listsoluong.Add(intValueSL);
                        }
                    }
                    if (key.Contains("Gia_"))
                    {
                        gia += form[key] + ";#";
                        listgia.Add(gia);
                    }
                    if (key.Contains("DonVi"))
                    {
                        donvi += form[key] + ";#";
                    }
                }

                ////Validate so luong san pham trong kho
                for (int i = 0; i < listmasp.Count; i++)
                {
                    string ma_sp_select = listmasp[i];
                    if (!string.IsNullOrEmpty(ma_sp_select))
                    {
                        SanPham sp = db.SanPhams.Where(p => p.MaSP == ma_sp_select).FirstOrDefault();
                        SanPhamInKho sanPhamInKho = db.SanPhamInKhoes.Where(s => s.SanPhamID == sp.ID && s.KhoID == xuatkho.KhoID).FirstOrDefault();
                        if (sanPhamInKho == null || sanPhamInKho.SoLuong < listsoluong[i])
                        {
                            return null;
                        }
                    }
                }

                decimal giatriThucte = 0;
                // update so luong san pham
                for (int i = 0; i < listmasp.Count; i++)
                {
                    string ma_sp_select = listmasp[i];
                    if (!string.IsNullOrEmpty(ma_sp_select))
                    {
                        SanPham sp = db.SanPhams.Where(p => p.MaSP == ma_sp_select).FirstOrDefault();
                        giatriThucte += Util.ConvertCurrencyToMoney(sp.GiaNhap) * listsoluong[i];
                        SanPhamInKho sanPhamInKho = db.SanPhamInKhoes.Where(s => s.SanPhamID == sp.ID && s.KhoID == xuatkho.KhoID).FirstOrDefault();
                        if (sanPhamInKho == null || sanPhamInKho.SoLuong < listsoluong[i])
                        {
                            return null;
                        }
                        else
                        {
                            sanPhamInKho.SoLuong -= listsoluong[i];
                            db.Entry(sanPhamInKho).State = EntityState.Modified;
                            db.SaveChanges();
                        }
                    }
                }

                xuatkho.Ma_SP = masp;
                xuatkho.SoLuong = soluong;
                xuatkho.Gia = gia;
                xuatkho.DonVi = donvi;
                xuatkho.Lai = Util.ConvertDecimaToCurrency(Util.ConvertCurrencyToMoney(xuatkho.TongThanhToan) - giatriThucte);

                //update tổng nợ Khách hàng
                int idKH = Convert.ToInt32(xuatkho.ID_KhachHang);
                KhachHang khachhang = db.KhachHangs.Find(idKH);
                var tongno = Util.ConvertCurrencyToMoney(khachhang.TongNo) + Util.ConvertCurrencyToMoney(xuatkho.TongThanhToan);
                khachhang.TongNo = Util.ConvertDecimaToCurrency(tongno);
                db.Entry(khachhang).State = EntityState.Modified;

                //Tao moi nhap kho
                db.XuatKhoes.Add(xuatkho);
                db.SaveChanges();
                if (form["submit"] == "Lưu & in hóa đơn")
                {
                    int idAfterSave = xuatkho.ID;
                    return RedirectToAction("Details", new { id = idAfterSave });
                }
                else
                {
                    return RedirectToAction("IndexGrid");
                }
            }

            ViewBag.ID_KhachHang = new SelectList(db.KhachHangs.OrderBy(p => p.TenKH), "ID", "MaKH", xuatkho.ID_KhachHang);
            List<Kho> khoes = new List<Kho>();
            foreach (var userInCuaHang in currentUser.UserInCuaHangs)
            {
                khoes.AddRange(userInCuaHang.CuaHang.Khoes);
            }
            ViewBag.KhoID = new SelectList(khoes.OrderBy(p => p.TenKho), "ID", "TenKho");
            ViewBag.CurrentUserDisplayName = currentUser.DisplayName;
            ViewBag.CurrentUserID = currentUser.UserId;
            
            return View(xuatkho);
        }

        //
        // GET: /XuatKho/Edit/5
        [Authorize(Roles = "Administrator,StaffXuatKho")]
        public ActionResult Edit(int id = 0)
        {
            var currentUser = db.UserProfiles.Where(u => u.UserName == User.Identity.Name).FirstOrDefault();
            if (currentUser == null) return RedirectToAction("Index", "Home");
            XuatKho xuatkho = db.XuatKhoes.Find(id);
            if (xuatkho == null || xuatkho.KhachHang.CuaHangID != Convert.ToInt32(Session["CuaHangID"]))
            {
                return HttpNotFound();
            }

            var masp = xuatkho.Ma_SP;
            var soluong = xuatkho.SoLuong;
            var gia = xuatkho.Gia;
            var donvi = xuatkho.DonVi;
            var listmasanpham = masp.Split(new string[] { ";#" }, StringSplitOptions.None);
            ViewBag.listmasp = listmasanpham;
            ViewBag.listsoLuong = soluong.Split(new string[] { ";#" }, StringSplitOptions.None);
            ViewBag.listgia = gia.Split(new string[] { ";#" }, StringSplitOptions.None);
            ViewBag.listDonvi = donvi.Split(new string[] { ";#" }, StringSplitOptions.None);
            ViewBag.stt = listmasanpham.Length;

            ViewBag.TenKho = xuatkho.Kho.TenKho;
            ViewBag.CurrentUserDisplayName = currentUser.DisplayName;
            ViewBag.CurrentUserID = currentUser.UserId;
            ViewBag.ID_KhachHang = new SelectList(db.KhachHangs.OrderBy(p => p.TenKH), "ID", "MaKH", xuatkho.ID_KhachHang);

            @ViewBag.makhachhang = xuatkho.KhachHang.MaKH;
            @ViewBag.tenkhachhang = xuatkho.KhachHang.TenKH;
            @ViewBag.diachikhachhang = xuatkho.KhachHang.DiaChiKH;
            return View(xuatkho);
        }
        // GET: Quy trình

        [Authorize(Roles = "Administrator,StaffXuatKho")]
        public ActionResult QuyTrinh()
        {
            return View();
        }

        [Authorize(Roles = "Administrator,StaffXuatKho")]
        public ActionResult ThanhToan(int id)
        {
            XuatKho xk = db.XuatKhoes.Find(id);
            if (xk == null || xk.KhachHang.CuaHangID != Convert.ToInt32(Session["CuaHangID"]))
            {
                return HttpNotFound();
            }

            if (ModelState.IsValid)
            {
                xk.IsThanhToan = "yes";
                db.Entry(xk).State = EntityState.Modified;
                db.SaveChanges();
                //return RedirectToAction("Index");
            }
            return View(xk);
        }

        //
        // POST: /XuatKho/Edit/5
        [Authorize(Roles = "Administrator,StaffXuatKho")]
        [HttpPost]
        public ActionResult Edit(XuatKho xuatkho, FormCollection form)
        {
            //remove old infomation
            int id = Convert.ToInt32(xuatkho.ID);
            var oldXK = db.XuatKhoes.Find(id);
            var old_Masp = oldXK.Ma_SP;
            var old_SoLuong = oldXK.SoLuong;
            var idold_kh = oldXK.ID_KhachHang;
            if (oldXK.KhachHang.CuaHangID != Convert.ToInt32(Session["CuaHangID"]))
            {
                return RedirectToAction("Index", "Home");
            }

            if (ModelState.IsValid)
            {
                string masp = string.Empty;
                string soluong = string.Empty;
                string gia = string.Empty;
                string donvi = string.Empty;
                List<string> listmasp = new List<string>();
                List<int> listsoluong = new List<int>();
                List<string> listgia = new List<string>();
                foreach (string key in form.AllKeys)
                {
                    if (key.Contains("ma_sp"))
                    {
                        masp += form[key] + ";#";
                        listmasp.Add(form[key]);
                    }
                    if (key.Contains("SoLuong_"))
                    {
                        soluong += form[key] + ";#";
                        listsoluong.Add(Convert.ToInt32(form[key]));
                    }
                    if (key.Contains("Gia_"))
                    {
                        gia += form[key] + ";#";
                        listgia.Add(gia);
                    }
                    if (key.Contains("DonVi"))
                    {
                        donvi += form[key] + ";#";
                    }
                }

                if (!string.IsNullOrEmpty(old_Masp))
                {
                    var list_old_Masp = old_Masp.Split(new string[] { ";#" }, StringSplitOptions.None);
                    var list_old_SoLuong = old_SoLuong.Split(new string[] { ";#" }, StringSplitOptions.None);
                    ////Validate so luong san pham trong kho
                    for (int i = 0; i < list_old_Masp.Length; i++)
                    {
                        string sp_old_sp = list_old_Masp[i];
                        if (!string.IsNullOrEmpty(sp_old_sp))
                        {
                            SanPham sp = db.SanPhams.Where(p => p.MaSP == sp_old_sp).FirstOrDefault();
                            if (sp != null)
                            {
                                SanPhamInKho sanPhamInKho = db.SanPhamInKhoes.Where(s => s.SanPhamID == sp.ID && s.KhoID == xuatkho.KhoID).FirstOrDefault();
                                if (sanPhamInKho == null || (sanPhamInKho.SoLuong + Convert.ToInt32(list_old_SoLuong[i]) - listsoluong[i]) < 0)
                                {
                                    return null;
                                }
                            }
                        }
                    }

                    for (int i = 0; i < list_old_Masp.Length; i++)
                    {
                        string sp_old_sp = list_old_Masp[i];
                        if (!string.IsNullOrEmpty(sp_old_sp))
                        {
                            SanPham sp = db.SanPhams.Where(p => p.MaSP == sp_old_sp).FirstOrDefault();
                            if (sp != null)
                            {
                                SanPhamInKho sanPhamInKho = db.SanPhamInKhoes.Where(s => s.SanPhamID == sp.ID && s.KhoID == xuatkho.KhoID).FirstOrDefault();
                                if (sanPhamInKho != null)
                                {
                                    sanPhamInKho.SoLuong += Convert.ToInt32(list_old_SoLuong[i]);
                                    db.Entry(sanPhamInKho).State = EntityState.Modified;
                                    db.SaveChanges();
                                }
                            }
                        }
                    }
                }

                decimal giatriThucte = 0;
                for (int i = 0; i < listmasp.Count; i++)
                {
                    string ma_sp_select = listmasp[i];
                    SanPham sp = db.SanPhams.Where(p => p.MaSP == ma_sp_select).FirstOrDefault();
                    giatriThucte += Util.ConvertCurrencyToMoney(sp.GiaNhap) * listsoluong[i];
                    SanPhamInKho sanPhamInKho = db.SanPhamInKhoes.Where(s => s.SanPhamID == sp.ID && s.KhoID == xuatkho.KhoID).FirstOrDefault();
                    if (sanPhamInKho != null)
                    {
                        sanPhamInKho.SoLuong -= listsoluong[i];
                        db.Entry(sanPhamInKho).State = EntityState.Modified;
                        db.SaveChanges();
                    }
                }
                
                //re-Update Tong No
                KhachHang old_KH = db.KhachHangs.Find(idold_kh);
                var new_tongno_dvcc = Util.ConvertCurrencyToMoney(old_KH.TongNo) - Util.ConvertCurrencyToMoney(oldXK.TongThanhToan) + Util.ConvertCurrencyToMoney(xuatkho.TongThanhToan);
                old_KH.TongNo = Util.ConvertDecimaToCurrency(new_tongno_dvcc);
                db.Entry(old_KH).State = EntityState.Modified;

                xuatkho.Ma_SP = masp;
                xuatkho.SoLuong = soluong;
                xuatkho.Gia = gia;
                xuatkho.DonVi = donvi;
                xuatkho.Lai = Util.ConvertDecimaToCurrency(Util.ConvertCurrencyToMoney(xuatkho.TongThanhToan) - giatriThucte);
                this.db.Entry<XuatKho>(oldXK).CurrentValues.SetValues(xuatkho);
                db.SaveChanges();
                if (form["submit"] == "Lưu & in hóa đơn")
                {
                    int idAfterSave = xuatkho.ID;
                    return RedirectToAction("Details", new { id = idAfterSave });
                }
                else
                {
                    return RedirectToAction("IndexGrid");
                }
            }
            ViewBag.ID_KhachHang = new SelectList(db.KhachHangs, "ID", "MaKH", xuatkho.ID_KhachHang);
            ViewBag.ID_NguoiXuatKho = new SelectList(db.UserProfiles, "UserId", "Code", xuatkho.ID_NguoiXuatKho);
            return View(xuatkho);
        }

        //
        // GET: /XuatKho/Delete/5
        [Authorize(Roles = "Administrator,StaffXuatKho")]
        public ActionResult Delete(int id = 0)
        {
            XuatKho xuatkho = db.XuatKhoes.Find(id);
            // update gia tri cu trong kho
            if (xuatkho == null || xuatkho.KhachHang.CuaHangID != Convert.ToInt32(Session["CuaHangID"]))
            {
                return HttpNotFound();
            }

            var old_Masp = xuatkho.Ma_SP;
            var old_SoLuong = xuatkho.SoLuong;
            var idold_kh = xuatkho.ID_KhachHang;
            if (!string.IsNullOrEmpty(old_Masp))
            {
                var list_old_Masp = old_Masp.Split(new string[] { ";#" }, StringSplitOptions.None);
                var list_old_SoLuong = old_SoLuong.Split(new string[] { ";#" }, StringSplitOptions.None);
                for (int i = 0; i < list_old_Masp.Length; i++)
                {

                    string sp_old_sp = list_old_Masp[i];
                    if (!string.IsNullOrEmpty(sp_old_sp))
                    {
                        SanPham sp = db.SanPhams.Where(p => p.MaSP == sp_old_sp).FirstOrDefault();
                        if (sp != null)
                        {
                            SanPhamInKho sanPhamInKho = db.SanPhamInKhoes.Where(s => s.SanPhamID == sp.ID && s.KhoID == xuatkho.KhoID).FirstOrDefault();
                            if (sanPhamInKho != null)
                            {
                                sanPhamInKho.SoLuong += Convert.ToInt32(list_old_SoLuong[i]);
                                db.Entry(sanPhamInKho).State = EntityState.Modified;
                                db.SaveChanges();
                            }
                        }
                    }
                }
            }
            //update tong no khach hang
            KhachHang old_KH = db.KhachHangs.Find(idold_kh);
            var new_tongno_dvcc = Util.ConvertCurrencyToMoney(old_KH.TongNo) - Util.ConvertCurrencyToMoney(xuatkho.TongThanhToan);
            old_KH.TongNo = Util.ConvertDecimaToCurrency(new_tongno_dvcc);
            db.Entry(old_KH).State = EntityState.Modified;

            db.XuatKhoes.Remove(xuatkho);
            db.SaveChanges();
            return RedirectToAction("IndexGrid");
        }

        //
        // POST: /XuatKho/Delete/5
        //[Authorize(Roles = "Administrator,StaffXuatKho")]
        //[HttpPost, ActionName("Delete")]
        //public ActionResult DeleteConfirmed(int id)
        //{
        //    XuatKho xuatkho = db.XuatKhoes.Find(id);
        //    // update gia tri cu trong kho

        //    var old_Masp = xuatkho.Ma_SP;
        //    var old_SoLuong = xuatkho.SoLuong;
        //    var idold_kh = xuatkho.ID_KhachHang;
        //    if (!string.IsNullOrEmpty(old_Masp))
        //    {
        //        var list_old_Masp = old_Masp.Split(new string[] { ";#" }, StringSplitOptions.None);
        //        var list_old_SoLuong = old_SoLuong.Split(new string[] { ";#" }, StringSplitOptions.None);
        //        for (int i = 0; i < list_old_Masp.Length; i++)
        //        {

        //            string sp_old_sp = list_old_Masp[i];
        //            if (!string.IsNullOrEmpty(sp_old_sp))
        //            {
        //                SanPham sp = db.SanPhams.Where(p => p.MaSP == sp_old_sp).FirstOrDefault();
        //                sp.SoLuong = sp.SoLuong + Convert.ToInt32(list_old_SoLuong[i]);
        //                db.Entry(sp).State = EntityState.Modified;
        //                db.SaveChanges();
        //            }
        //        }
        //    }
        //    //update tong no khach hang
        //    KhachHang old_KH = db.KhachHangs.Find(idold_kh);
        //    var new_tongno_dvcc = Util.ConvertCurrencyToMoney(old_KH.TongNo) - Util.ConvertCurrencyToMoney(xuatkho.TongThanhToan);
        //    old_KH.TongNo = Util.ConvertDecimaToCurrency(new_tongno_dvcc);
        //    db.Entry(old_KH).State = EntityState.Modified;

        //    db.XuatKhoes.Remove(xuatkho);
        //    db.SaveChanges();
        //    return RedirectToAction("Index");
        //}

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}